package com.lhy.hierarchy.ruleEngine.composite.listener;

import com.hauxsoft.core.constant.Consts;
import com.hauxsoft.core.mvc.dao.SqlFieldOperatorEnum;
import com.hauxsoft.core.util.StringUtils2;
import com.hauxsoft.entity.JavaRuleDO;
import com.hauxsoft.service.JavaRuleService;
import com.hauxsoft.utils.BaseRule;
import com.hauxsoft.utils.DynamicRuleUtils;
import com.hauxsoft.utils.JavaRuleStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Arrays;
import java.util.List;

/**
 * 应用启动监听器
 * @author z_hh  
 * @date 2018年12月10日
 */
@Slf4j
@WebListener
public class AppRunListener implements ServletContextListener {
	
	@Value("${dynamic.rule.target}")
	private String ruleTarget;
	
	/**
	 * 将指定组的javaRule对象装进容器
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		if (StringUtils2.notEmpty(ruleTarget)) {
			List<JavaRuleDO> javaRules = javaRuleService.createJpaQuery()
				.where("status", Consts.Entity.IS_VALID)
				.where("target", SqlFieldOperatorEnum.IN, Arrays.asList(ruleTarget.split(",")))
				.list();
			javaRules.stream()
				.forEach(javaRule -> {
					try {
						BaseRule rule = DynamicRuleUtils.getRuleInstance(javaRule);
						if (!javaRuleStorage.add(javaRule.getGroupName(), rule)) {
							log.warn("添加规则{}到容器失败！", javaRule.getName());
							javaRule.setStatus(Consts.Entity.NOT_VALID);
							javaRuleService.save(javaRule);
						}
						log.info("添加了规则{}到容器", javaRule.getFullClassName());
					} catch (Exception e) {
						log.warn("添加规则{}到容器异常！", javaRule.getName());
						javaRule.setStatus(Consts.Entity.NOT_VALID);
						javaRuleService.save(javaRule);
					}
					
				});
		}
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		// 
	}
	
	@Autowired
	private JavaRuleService javaRuleService;
	@Autowired
	private JavaRuleStorage javaRuleStorage;
}
